const BASE_URL = "http://192.168.2.28:6060";
const TEST_URL = "http://192.168.2.28:6060";

const http = (options) => {
	return new Promise((resolve, reject) => {
		// GET 请求头 X-FORM格式
		const FROM = {
			'content-type': 'application/x-www-form-urlencoded',
			// 'Authorization': 'Bearer b945f6ec-76f0-4943-9a8b-cccea74fb809',
		};
		// POST 请求头 JSON格式
		const JSON = {
			'content-type': 'application/json',
			'Authorization': uni.getStorageSync('Token'),
		};
		uni.getNetworkType({
			success: (res) => {
				if (res.networkType == 'none') {
					uni.navigateTo({
						url: '/pages/noNetwork'
					})
				} else {
					try {
						uni.request({
							url:"/api"+ options.url,
							method: options.method || 'GET',
							header: options.method == 'POST' ? JSON : FROM,
							data: options.data || {},
							success: (res) => {
								if (res.statusCode != 200) {
									if (res.statusCode == 500 || res.statusCode ==
										502 || res.statusCode == 504) {
										uni.showToast({
											title: '服务器错误',
											icon: 'none'
										})
									} else if (res.statusCode == 403) {
										uni.showToast({
											title: '无权限',
											icon: 'none'
										})
									} else {
										uni.showToast({
											title: res.data.error?res.data.error:String(res.statusCode),
											icon: 'none'
										})
									}
								} else {
									// 获取oss单独处理
									if (options.url == 'public/getOssToken') {
										if (res.data.StatusCode != 200) {
											uni.showToast({
												title: res.data.msg,
												icon: 'none'
											})
										} else {
											resolve(res.data)
										}
									} else {
										if (res.data.code != '000000') {
											if (res.data.code == 'ERR401') {
												//token失效
												uni.clearStorage();
												setTimeout(() => {
													uni.navigateTo({
														url: '/pages/login/login'
													})
												}, 1500)
											}
											uni.showToast({
												title: res.data.msg ==
													'无效的token' ? '登录过期' :
													res.data.msg,
												icon: 'none'
											})
										} else {
											resolve(res.data)
										}
									}
								}
							},
							fail: (err) => {
								reject(err);
								uni.showToast({
									title: '请求失败',
									icon: 'none'
								})
							}
						})
					} catch (e) {
						//TODO handle the exception
						console.log(e);
						uni.showToast({
							title: '请求异常',
							icon: 'none'
						})
					}
				}
			},
		});

	})
}
export default http
